package com.llyb.tingshu.user.strategy.impl;

import com.llyb.tingshu.model.user.UserInfo;
import com.llyb.tingshu.model.user.UserVipService;
import com.llyb.tingshu.model.user.VipServiceConfig;
import com.llyb.tingshu.user.mapper.UserInfoMapper;
import com.llyb.tingshu.user.mapper.UserVipServiceMapper;
import com.llyb.tingshu.user.mapper.VipServiceConfigMapper;
import com.llyb.tingshu.user.strategy.ItemTypeStrategy;
import com.llyb.tingshu.vo.user.UserPaidRecordVo;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("1003")
public class VipStrategy implements ItemTypeStrategy {


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    /**
     * 保存付费记录
     *
     * @param userPaidRecordVo
     */
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {

        // vip会员  判断是否已经是会员，续期或新增
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        Date currentDate = new Date();
        UserVipService userVipService = new UserVipService();
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setStartTime(currentDate);

        if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(currentDate)) {
            currentDate = userInfo.getVipExpireTime();
        }/*else {
			}*/
        // 购买的月数
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(userPaidRecordVo.getItemIdList().get(0));
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        LocalDateTime currentDateTime = new LocalDateTime(currentDate);
        Date expireTime = currentDateTime.plusMonths(serviceMonth).toDate();

        userVipService.setExpireTime(expireTime);
        userVipServiceMapper.insert(userVipService);

        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(expireTime);
        userInfoMapper.updateById(userInfo);
    }
}
